<?php

namespace App\Http\Controllers\Back;

use App\Http\Controllers\Controller;
use App\Model\Salesmen;
use App\Model\SmsMsg;
use App\Model\UserUp;
use Illuminate\Http\Request;
use App\User;
use Illuminate\Support\Facades\DB;

/**
 * 会员转变业务员，业务员转变会员改变...
 * Class UserChangeController
 * @package App\Http\Controllers\Back
 */
class UserChangeController extends Controller
{
    /**
     * 会员转变业务员
     */
    public function userToSalesmen(Salesmen $salesmen, Request $request, SmsMsg $msg )
    {
        // 只有运营商才能操作
        if ($request->user()->type != 2) {
            return $this->fail('无权操作');
        }

        // 查询运营商是否满元
        $count = User::where('operator_id',$request->user()->id)->where('type', '3')->count();
        if ($count >= 10) {
            return $this->fail('业务员数量到达上限');
        }

        $phone = $request->input("phone"); // 手机
        $code = $request->input ( "code" );
        // 验证短信
        if ($phone != "15802302783") {
            $msg->validate ( $phone, $code );
        }

        $u = new User;
        $userInfo = $u->where('phone', '=', $phone)->first();
        // 是否由业务员变为会员,0可以改变，1不能改变
        if ($userInfo->is_change_grade == 1) {
            return $this->fail('该账户易经改变过一次业务员，不能再次改变');
        }
        if ($userInfo->type != 4) {
            return $this->fail('该用户不是会员');
        }

        try {
            DB::beginTransaction();

            // 将该会员改变为业务员
            $this->inputUserSave($salesmen, $request, $userInfo->id);
            // 改变会员表信息
            $this->changeUserInfo($userInfo, $request, $request->user()->place_partner_id);
            // 改变会员下级所有信息
            $this->changeSubUserInfo($userInfo->id,$request->user()->id,$request->user()->place_partner_id);

            DB::commit();
            return $this->success('操作完成');
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->error('添加失败' . $e->getMessage());
        }
    }

    /**
     * 将会员转业务员数据写入salesmen表
     * @param $salesmen
     * @param $request
     * @param $user_id
     * @throws \Exception
     */
    public function inputUserSave($salesmen, $request, $user_id)
    {
        $this->validate($request, [
            'name' => 'required',
            'id_card' => 'required',
            'id_card_img_positive' => 'required',
            'id_card_img_negative' => 'required',
            'province_id' => 'required',
            'city_id' => 'required',
            'area_id' => 'required',
            'phone' => 'required',
            'bank_card_name' => 'required',
            'bank_card_no' => 'required',
            'bank_name' => 'required',
        ]);

        $name = $request->input("name"); // 会员名称
        $id_card = $request->input("id_card"); // 身份证号码
        $id_card_img_positive = $request->input("id_card_img_positive"); // 证件照片正面
        $id_card_img_negative = $request->input("id_card_img_negative"); // 证件照片反面
        $province_id = $request->input("province_id"); // 省
        $city_id = $request->input("city_id"); // 市
        $area_id = $request->input("area_id"); // 区
        $phone = $request->input("phone"); // 手机
        $bank_card_name = $request->input("bank_card_name"); // 银行卡账户名
        $bank_card_no = $request->input("bank_card_no"); // 银行账号
        $bank_name = $request->input("bank_name"); // 所属银行

        if ($salesmen->where('phone', $phone)->first()) {
            throw new \Exception("该手机号码存在");
        }

        $salesmen->name = $name;
        $salesmen->id_card = $id_card;
        $salesmen->id_card_img = $id_card_img_positive . ',' . $id_card_img_negative;
        $salesmen->province_id = $province_id;
        $salesmen->city_id = $city_id;
        $salesmen->area_id = $area_id;
        $salesmen->phone = $phone;
        $salesmen->bank_card_name = $bank_card_name;
        $salesmen->bank_card_no = $bank_card_no;
        $salesmen->bank_name = $bank_name;
        $salesmen->user_id = $user_id;

        $salesmen->save();
    }

    // 改变会员表信息

    /**
     * @param $userInfo
     * @param $request
     * @param $place_partner_id
     */
    public function changeUserInfo($userInfo, $request, $place_partner_id)
    {
        $userInfo->type = 3;
        $userInfo->pid = 0;
        $userInfo->account = $request->input("phone");
        $userInfo->salesman_id = 0;
        $userInfo->operator_id = $request->user()->id;
        $userInfo->place_partner_id = $place_partner_id;
        $userInfo->save();
    }

    // 改变会员下级所有信息

    /**
     * @param $user_id
     */
    public function changeSubUserInfo($user_id, $operator_id, $place_partner_id)
    {
        $userUp = UserUp::where("user_id", $user_id)->first();
        $user_up_list = $userUp->user_up_list;

        // 查询会员下级
        $regexp = $user_id . ',' . $user_up_list . '$';  // $regexp = '3,2,1,0$'
        $results = DB::select('SELECT * from user_up Where user_up_list REGEXP ?', [$regexp]);

        if (is_array($results)) {
            $results = \GuzzleHttp\json_decode(\GuzzleHttp\json_encode($results), true);
            $arr = array_column($results, 'user_id');
            // 修改无线子用户salesman_id operator_id place_partner_id
            DB::table('users')->whereIn('id', $arr)->update(['salesman_id' => $user_id, 'operator_id'=>$operator_id, 'place_partner_id' => $place_partner_id]);
        }

        if ($userUp->user_up_list != "0") {
            /**
             * 如果会员 user_id=3  user_up_list="2,1,0" 升级业务员
             *  例：
             *  user_id     user_up_list  => 升级改变  user_up_list
             *   1              0
             *   2              1,0
             *   3              2,1,0                   0
             *   4              3,2,1,0                 3,0
             *   5              2,1,0
             *   6              5,2,1,0
             *   7              6,5,2,1,0
             *   8              3,2,1,0                 3,0
             *  修改下级会员
             *   sql = Update user_up SET list = REPLACE(list, "3,2,1,0", "3,0") Where list REGEXP '3,2,1,0$'
             */
            // 修改user_up_list值"2,1,0" =>"0"
            $userUp->user_up_list = "0";
            $userUp->save();

            if (is_array($results)) {
                DB::update('Update user_up SET `user_up_list` = REPLACE(`user_up_list`, ?, ?) Where `user_up_list` REGEXP ?', [
                    $user_up_list,
                    '0',
                    $regexp]);

            }
        }

        //if ($userUp->user_up_list == "0"){
        /**不变
         * 比如修改 user_id=9  user_up_list=0
         *  user_id     user_up_list => 升级改变  user_up_list
         *   9              0
         *   10             9,0
         *   11             10,9,0
         */
        //}
    }

    public function aa()
    {
        $user = User::select("id", "pid", "type")->whereIn('type', [3, 4])->get()->toArray();
//        print_r($user);exit;
        $tree = $this->getTree($user, ['id' => '', 'name' => '']);
//        print_r($tree);

    }

    public function getTree(&$data, $d)
    {
        $sign = '';
        foreach ($data as $k => $v) {
            if ($v['pid'] == $d['id']) {        //父亲找到儿子

                if ($v['pid'] != 0) {
                    $sign = ',';
                }
                $v['name'] = $v['pid'] . $sign . $d['name'];
                $data[$k]['name'] = $v['pid'] . $sign . $d['name'];
                $this->getTree($data, $v);
            }
        }

        return $data;
    }

//    public function getTree($data, $d)
//    {
//        $tree = [];
//        $biao = '';
//
//        foreach($data as $k => $v)
//        {
//            if($v['pid'] == $d['id'])
//            {        //父亲找到儿子
//
//                if ($v['pid'] !=0) {
//                    $biao = '-';
//                }
//                $v['name'] = $v['pid'] . $biao . $d['name'];
//
//                $data[$k]['name'] = $v['pid'] . $biao . $d['name'];
//
////                var_dump($v);
//                $v['sub'] = $this->getTree($data, $v);
//
////                $this->getTree($data, $v);
//                $tree[] = $v;
//
//            }
//        }
//
//        return $tree;
//    }


    /**
     * 业务员转变会员
     */
    public function SalesmenToUser(Request $request){
        $user_id = $request->input("user_id");
        if (empty($user_id)) {
            return $this->fail('404');
        }
        $userInfo = User::where('id', $user_id)->where('operator_id', $request->user()->id)->first();
        if (!$userInfo || $userInfo->type != 3){
            return $this->fail('401');
        }

        try {
            DB::beginTransaction();

            // 新增虚拟会员
            $user = new User();
            $user->type = 3;
            $user->is_fase_distribution = 1; // 虚拟会员
            $user->operator_id = $request->user()->id;
            $user->place_partner_id = $request->user()->place_partner_id;
            $user->save();

            $user_up = new UserUp();
            $user_up->user_id = $user->id; // 虚拟会员写入user_up表
            $user_up->user_up_list = 0;
            $user_up->save();

            // 修改业务员对应该虚拟会员
            $salesmen = new Salesmen();
            $salesmen->user_id = $user->id; // 虚拟会员id
            $salesmen->save();

            // 将会员与虚拟会员关系对应
            $user_up_info = UserUp::where('user_id', $user_id)->first();
            $user_up_info->user_up_list = $user->id .',0';
            $user_up_info->save();

            // 修改业务员状态
            User::where("id", $user_id)->update([
                'type' => 4,
                'pid' => $user->id,
                'salesman_id' => $user->id,
                'is_change_grade' => 1
            ]);
            // 业务员下面所有会员的salesman_id改变为新增虚拟会员id
            User::where("salesman_id", $userInfo->id)->update([
                'salesman_id' => $user->id
            ]);

            DB::commit();
            return $this->success('操作完成');
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->error('添加失败');
        }
    }
}